import subprocess
import rrd_base
import re
import time

import color

try:
    from pyrrd.rrd import DataSource, RRA, RRD
    from pyrrd.graph import DEF, CDEF, VDEF
    from pyrrd.graph import LINE, AREA, GPRINT
    from pyrrd.graph import ColorAttributes, Graph
except:
    print "Couldn't load required modules. You probably need to install it with:"
    sys.exit('sudo apt-get install python-pyrrd python-pysnmp4')

class RrdFS(rrd_base.RrdBase):
    def __init__(self, domain, name, mountpoint):
        super(RrdFS,self).__init__(domain=domain, group="filesystem", instance=name)
        self.mountpoint = mountpoint

    def create_file(self):
        dataSources = []
        for ds in ["used", "available"]:
            dataSources.append(DataSource( dsName=ds, dsType='GAUGE', heartbeat=self.heartbeat()))

        roundRobinArchives = []
        for func in ['AVERAGE', 'MAX', 'MIN']:
            for step,row in self.rra_pattern():
                roundRobinArchives.append(RRA(cf=func, xff=0.5, steps=step, rows=row))

        self.myRRD = RRD(self.filename, ds=dataSources, rra=roundRobinArchives, step=self.data_step())
        self.myRRD.create()

    def update(self):
        df = subprocess.Popen(["/bin/df", "{0}".format(self.mountpoint)], shell=False, stdout=subprocess.PIPE)
        data = df.communicate()[0]
        words = data.split("\n")[1].split()
        # ['/dev/mapper/whole-root', '7785688', '5841968', '1865612', '76%', '/']
        self.myRRD.bufferValue(int(round(time.time())), 1024*int(words[2]), 1024*int(words[3]))
        self.myRRD.update()

    def graph(self):
        def_u  =  DEF(rrdfile=self.myRRD.filename, vname='u',  cdef="AVERAGE", dsName='used')
        def_a  =  DEF(rrdfile=self.myRRD.filename, vname='a',  cdef="AVERAGE", dsName='available')
        def_um =  DEF(rrdfile=self.myRRD.filename, vname='um', cdef="MAX", dsName='used')
        v_um   = VDEF(vname="v", rpn="{0},MAXIMUM".format(def_um.vname))
        area_u = AREA(defObj=def_u,  color=color.RGBA['red'],   legend="Used",      stack=True)
        area_a = AREA(defObj=def_a,  color=color.RGBA['green'], legend="Available", stack=True)
        line_0 = LINE(2, defObj=v_um,color=color.RGBA['black'],  legend="Peak")

        for tf in self.graph_time_frames().keys():
            g = Graph(self.image_name(tf),
                      start=int(time.time())-self.graph_time_frames()[tf], end=int(time.time()),
                      lower_limit=0.000001,
                      base=1024,
                      title='"Filesystem Usage for {0}/{1} - Updated {2}"'.format(self.data_domain, self.data_instance, time.strftime("%Y%m%d at %H:%M")),
                      height=self.graph_height, width=self.graph_width,
                      x_grid=self.grid[tf],
                      step=self.graph_step_times[tf])
            g.data.extend([def_u, def_a, area_u, area_a, def_um, v_um, line_0])
            g.write()

            if False:
                g = Graph(self.icon_name(tf),
                          start=int(time.time())-self.graph_time_frames()[tf], end=int(time.time()),
                          lower_limit=0.000001,
                          base=1024,
                          no_legend=True,
                          height=self.icon_height, width=self.icon_width,
                          step=self.graph_step_times[tf])
                g.data.extend([def_u, def_a, area_u, area_a])
                g.write()
